<template>
  <div class="pullRefresh" @touchstart="touchstart" ref="pullRefesh">
    <div class="refreshHead">{{msg}}</div>
    <slot>暂无内容</slot>
  </div>
</template>

<script>
export default {
  name: 'PullRefresh',
  props: ['value'],
  data (){
    return {
      msg: ''
    }
  },
  mounted (){
    console.log(this.$slots)
  },
  methods: {
    touchstart (e){
      this.pageY = e.touches[0].pageY
      this.pageX = e.touches[0].pageX
      this.$refs.pullRefesh.addEventListener('touchmove', this.touchmove, false)
    },
    touchmove (e){
      const move = e.touches[0].pageY - this.pageY
      const moveX = e.touches[0].pageX - this.pageX
      // 排除横向滑动
      if (Math.abs(moveX) > 50) {
        document.ontouchend = null
        return
      }
      if (!this.$refs.pullRefesh) return
      let translate = move / 2
      if (translate > 0 && translate <= 50){
        this.msg = '下拉即可刷新...'
      } else if (translate > 50 && translate < 150){
        translate = translate >= 250 ? 250 : translate
        this.$refs.pullRefesh.addEventListener('touchend', this.touchend, false)
        this.msg = '释放即可刷新...'
      }
      this.$refs.pullRefesh.style.transform = `translateY(${translate}px)`
      this.$refs.pullRefesh.style.transition = 'none'
    },
    async touchend (e){
      this.msg = '数据加载中...'
      this.$refs.pullRefesh.style.transition = 'all 300ms ease-in'
      this.$refs.pullRefesh.style.transform = `translateY(${100}px)`
      await this.$slots.default[0].componentInstance.getRank()
      await this._help.sleep(1500)
      this.msg = ''
      this.$refs.pullRefesh.style.transform = `translateY(${0}px)`
      this.$refs.pullRefesh.removeEventListener('touchend', this.touchend)
    }
  }
}
</script>

<style lang="less" scoped>
  .pullRefresh{
    .refreshHead{
      text-align: center;
      font-size: .8rem;
      color: var(--icon-color);
      transform: translateY(-100%);
    }
  }
</style>>
